package chapter11.section6;
/*程序CLerk 模拟银行职员*/

import java.util.Random;

public class Clerk extends Thread {
    private final QueueMachine queue;// 排队机的引用
    private final String name;

    public Clerk(QueueMachine queue, String name) {
        super(name);
        this.queue = queue;
        this.name = name;
    }

    public Clerk(QueueMachine queue, String name, ThreadGroup group) {
        super(group, name);//将当前线程添加到一个指定的线程组内
        this.queue = queue;
        this.name = name;
    }


    @Override
    public void run() {
        Random rand = new Random();
        Transaction tran = null;
        String working = "woring";
        while (!working.equals("closed") || (!queue.isEmpty())) {
            try {
                tran = queue.get();
            } catch (InterruptedException e1) {
                working = "closed";
                continue;
            }
            System.out.println(this.name + "得到业务:" + tran);
            int newBalance = 0;// 记录业务完成后的新余额
            synchronized (tran.getAccount()) {
                if (tran.getTranType().compareTo(Transaction.DEPOSIT) == 0) {
                    newBalance = tran.getAccount().getBalance() + tran.getAmount();
                } else if (tran.getTranType().equals(Transaction.WITHDRAW)) {
                    newBalance = tran.getAccount().getBalance() - tran.getAmount();
                }
                /*
                 * 下面利用线程休眠控制每笔业务处理的时间长短不一，故意造成不同职员之间的不同步，以便展示可能出现的问题
                 * 如果休眠时被中断，则判断排队机中是否还有业务等待完成，没有的话，设置工作结束变量，退出循环，结束线程执行
                 */
                try {
                    Thread.sleep(rand.nextInt(200 + rand.nextInt(3)));
                } catch (InterruptedException e) {
                    working = "closed";
                }
                tran.getAccount().setBalance(newBalance);// 休眠后，更新账户余额
                System.out.printf(this.name + "完成%d号业务处理，处理后账户余额是%d\r\n", tran.getNum(), newBalance);
            }

        }

    }
}
